import React, { Component } from 'react';
import SiderTabbar from '/common/components/SiderTabbar';
import { connect } from 'dva';
import { forEach, isEmpty, filter, omit, find } from 'lodash';
import { comboTypes } from '@/globalConfig';

/**
 * 科目 - 用于报表中快速切换科目的场景，例如“账簿”中，对已选科目的切换
 */
@connect(({ global }) => ({
  global,
}))
export default class AccSiderTabbar extends Component {

  constructor(props) {
    super(props);
    this.state = {};
    this.activeObj = null;
    this.activeSubObj = null;
  }

  componentDidMount() {
    if (isEmpty(this.props.global[comboTypes.ACCOUNTING_ITEM_CATEGORY])) {
      this.props.dispatch({
        type: 'global/findByCode',
        payload: {
          code: comboTypes.ACCOUNTING_ITEM_CATEGORY,
        },
      });
    }
  }

  dealCompData() {
    const { global } = this.props;
    let dataList = this.props.dataList || [];
    let accTypeList = global[comboTypes.ACCOUNTING_ITEM_CATEGORY] || [];
    let reArr = [];
    let hadDefaultChecked = !isEmpty(this.props.defaultChecked);

    forEach(accTypeList, (typeItem) => {
      let dList = filter(dataList, (di) => (di && `${di.category}` === typeItem.code));
      let tItem = { ...typeItem, dataList: dList };
      reArr.push(tItem);

      if (hadDefaultChecked) {
        const activeSubObj = find(dList, (di) => (di && `${di.code}` === `${this.props.defaultChecked.code}`));
        if (!isEmpty(activeSubObj)) {
          this.activeSubObj = activeSubObj;
          this.activeObj = tItem;
          hadDefaultChecked = false;
        }
      }
    });
    return reArr;
  }

  render() {
    const compData = this.dealCompData();

    return (
      <SiderTabbar
        onChange={this.props.onChange}
        compData={compData}
        defaultActiveObj={this.activeObj}
        defaultActiveSubObj={this.activeSubObj}
      />
    );
  }
}

AccSiderTabbar.defaultProps = {
  defaultChecked: null,
  dataList: null,
  onChange: null,
};
